<template>
  <div class="edit-header" v-if="!onlyProduct">
    <p>广告组&商品</p>
  </div>
  <a-form v-if="!onlyProduct" ref="formRef" :disabled="adGroupIsDisabled" style="width: 900px" :model="editSpCampaignInfo" :rules="rulesUser">
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item field="adGroupName" label="广告组名称" label-col-flex="100px">
          <a-input v-model="editSpCampaignInfo.adGroupName" placeholder="请输入" allow-clear />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
  <div class="choose-product-w">
    <div class="head">商品</div>
    <div class="choose-product-con flex">
      <div class="choose-list">
        <a-tabs default-active-key="1">
          <a-tab-pane key="1" title="搜索">
            <div class="flex-c-sb" style="margin-bottom: 10px">
              <a-input-search v-model="searchVal.orKeyword" style="width: 340px" placeholder="按商品标题、ASIN、MSKU搜索" @search="searchByVal" search-button />
              <a-button type="text" @click="addProduct(productList)" v-if="!productIsDisabled">添加本页全部</a-button>
            </div>
            <a-scrollbar style="height: 300px; overflow: auto">
              <ul>
                <li class="product-item flex-c-sb" v-for="(item, i) in productList" :key="i">
                  <div class="flex-c">
                    <div class="img-w">
                      <ImgPopover :src="getMainUrl(item)">
                        <template #con>
                          <a-image width="60" height="60" fit="contain" :src="getMainUrl(item)" />
                        </template>
                      </ImgPopover>
                    </div>
                    <div class="item-info">
                      <p class="text-limit-two">{{ item.name }}</p>
                      <div class="flex-c">
                        <p style="margin-right: 20px">
                          <span>ASIN:</span>
                          <span class="highlight">{{ item.asin }}</span>
                        </p>
                        <p>
                          <span>SKU:</span>
                          <span class="highlight">{{ item.msku }}</span>
                        </p>
                      </div>
                    </div>
                  </div>
                  <div class="btn-w">
                    <a-space direction="vertical" align="center">
                      <a-button size="mini" type="primary" @click="addProduct([item])" :disabled="productIsDisabled">添加</a-button>
                      <p class="cursor highlight" style="margin-top: 5px" v-if="item.childs && item.childs.length > 0 && !productIsDisabled" @click="addProduct(item.childs)">添加变体</p>
                    </a-space>
                  </div>
                </li>
              </ul>
            </a-scrollbar>
            <a-pagination style="margin-top: 10px" size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
          </a-tab-pane>
          <a-tab-pane key="2" title="输入列表">
            <a-textarea :disabled="productIsDisabled" v-model="asinVal" placeholder="输入ASIN，一行一个" allow-clear style="height: 300px" />
            <div class="flex-c-sb">
              <p>不得包含特殊字符，如@、#、*、$、/等</p>
              <a-button size="mini" type="primary" @click="addProductByAsin" v-if="!productIsDisabled">添加</a-button>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
      <div class="checked-list">
        <div class="flex-c-sb">
          <p>已添加{{ editSpCampaignInfo.checkedProducts.length }}个商品</p>
          <p class="highlight cursor" type="text" @click="deleteAll" style="font-size: 12px" v-if="!productIsDisabled">全部删除</p>
        </div>
        <a-scrollbar style="height: 380px; overflow: auto">
          <ul>
            <li class="product-item flex-c-sb" v-for="(item, i) in editSpCampaignInfo.checkedProducts" :key="i">
              <div class="flex-c">
                <div class="img-w">
                  <ImgPopover :src="getMainUrl(item)">
                    <template #con>
                      <a-image width="60" height="60" fit="contain" :src="getMainUrl(item)" />
                    </template>
                  </ImgPopover>
                </div>
                <div class="item-info">
                  <p class="text-limit-two">{{ item.name }}</p>
                  <div class="flex-c">
                    <p style="margin-right: 20px">
                      <span>ASIN:</span>
                      <span class="highlight">{{ item.asin }}</span>
                    </p>
                    <p>
                      <span>SKU:</span>
                      <span class="highlight">{{ item.msku }}</span>
                    </p>
                  </div>
                </div>
              </div>
              <div class="btn-w">
                <a-button size="mini" type="text" @click="deleteProduct(i)" v-if="!productIsDisabled">移除</a-button>
              </div>
            </li>
          </ul>
        </a-scrollbar>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, watch, onMounted } from 'vue'
  import { getAmzProductSale } from '@/api/publish'
  import { Message } from '@arco-design/web-vue'
  import { DraftFinishStep } from '../../types'
  const props = defineProps({
    darftInfo: {
      type: Object,
      default: () => {},
    },
    shop: {
      type: Object,
      default: () => {},
    },
    onlyProduct: {
      type: Boolean,
      default: false,
    },
  })
  const emit = defineEmits(['change'])
  onMounted(async () => {
    // 有草稿箱
    if (props.darftInfo?.draftId) {
      editSpCampaignInfo.value.adGroupName = props.darftInfo.adGroupName
      let asins = props.darftInfo.products?.map((el: any) => el.asin)
      let list = (await getProductByAsin(asins)) || []
      addProduct(list)
    }
    getProductList()
  })
  const rulesUser = ref({
    adGroupName: [{ required: true, message: '请输入广告组名称' }],
  })
  const editSpCampaignInfo = ref<any>({
    checkedProducts: [],
  })
  const formRef = ref()
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const productList = ref<Array<any>>([])
  const tableLoading = ref(false)
  const total = ref(0)
  const asinVal = ref()
  const shopId = computed(() => props.shop?.id)
  // 根据当前流程节点判断是否可编辑
  let adGroupIsDisabled = computed(() => {
    let handlerFlow = props.darftInfo?.handlerFlow || 'INIT'
    let level = DraftFinishStep[handlerFlow]
    return Number(level) > 1 ? true : false
  })
  let productIsDisabled = computed(() => {
    let handlerFlow = props.darftInfo?.handlerFlow || 'INIT'
    let level = DraftFinishStep[handlerFlow]
    return Number(level) > 2 ? true : false
  })
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getProductList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getProductList()
  }
  // 通过条件查询列表
  function searchByVal() {
    searchVal.value.pageNum = 1
    getProductList()
  }
  // 显示图片
  function getMainUrl(row: any) {
    return row?.imageList?.[0]?.link
  }
  // 获取产品列表
  async function getProductList() {
    let shop = props.shop || {}
    if (!shop.shopId) return
    tableLoading.value = true
    const res: any = await getAmzProductSale({
      ...searchVal.value,
      orKeywordType: 'name,asin,msku',
      orKeyword: searchVal.value.orKeyword,
      sellerIdList: shop.sellerId,
      marketplaceIdList: shop.marketplaceId,
    })
    tableLoading.value = false
    productList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
  }
  // 添加产品
  async function addProduct(list: Array<any>) {
    // 去重
    list.forEach((el: any) => {
      let _index = editSpCampaignInfo.value.checkedProducts.findIndex((item: any) => item.id == el.id)
      if (_index == -1) {
        editSpCampaignInfo.value.checkedProducts.push(el)
      }
    })
    updateSpCampaignInfo()
  }
  // 根据ASIN获取商品信息
  async function getProductByAsin(asins: Array<any>) {
    if (!asins?.length) return []
    // let shop = props.shop || {}
    const res: any = await getAmzProductSale({
      pageSize: 200,
      pageNum: 1,
      keywordType: 'asin',
      keyword: asins?.join(','),
      searchType: 'exact',
      // sellerIdList: shop.sellerId,
      // marketplaceIdList: shop.marketplaceId,
    })
    return res?.data?.records || []
  }
  // 输入asin添加商品校验
  async function addProductByAsin() {
    if (!asinVal.value) {
      Message.error('请输入ASIN')
      return
    }
    const reg = new RegExp('[~!@#$^&*=《》?！@#￥&*{}【】‘；：。，、？]')
    if (reg.test(asinVal.value)) {
      Message.error('不得包含特殊字符，如@、#、*、$、/等')
      return
    }
    let asins = asinVal.value.split('\n')
    asins = asins.filter((el: string) => el?.trim())
    let list = (await getProductByAsin(asins)) || []
    addProduct(list)
  }
  // 刪除产品
  function deleteProduct(i: number) {
    editSpCampaignInfo.value.checkedProducts.splice(i, 1)
    updateSpCampaignInfo()
  }
  // 校验信息
  async function validateData() {
    if (!props.onlyProduct) {
      let valid = await formRef.value.validate((valid: any) => {
        return valid
      })
      if (valid) return false
    }
    if (!editSpCampaignInfo.value.checkedProducts.length) {
      Message.error('请最少选择一个商品')
      return false
    }
    return true
  }
  // 设置需要创建的数据
  function setCreateData() {
    let products = editSpCampaignInfo.value.checkedProducts.map((el: any) => {
      return {
        asin: el.asin,
        sku: el.msku,
      }
    })
    return {
      adGroupName: editSpCampaignInfo.value.adGroupName,
      products: products,
    }
  }
  // 删除全部
  function deleteAll() {
    editSpCampaignInfo.value.checkedProducts = []
    updateSpCampaignInfo()
  }
  // 需要实时保存的数据
  function updateSpCampaignInfo() {
    emit('change', 'products', editSpCampaignInfo.value.checkedProducts)
  }
  watch(shopId, () => {
    getProductList()
  })

  defineExpose({ validateData, setCreateData })
</script>
<style lang="less" scoped>
  .edit-header {
    background-color: var(--color-fill-2) !important;
    border-left: 2px solid rgb(var(--primary-6));
    line-height: 32px;
    font-size: 16px;
    margin-bottom: 20px;
    padding-left: 20px;
  }
  .choose-product-w {
    border: 1px solid var(--color-border);
    .head {
      padding: 6px 20px;
      border-bottom: 1px solid var(--color-border);
    }
    .choose-list {
      width: 50%;
      border-right: 1px solid var(--color-border);
    }
    .img-w {
      border: 1px solid var(--color-border);
      margin-right: 4px;
    }
    .product-item {
      margin-bottom: 5px;
      font-size: 12px;
      padding-right: 10px;
    }
    .item-info {
      flex: 1;
      max-width: 500px;
      margin-right: 5px;
    }
    :deep(.arco-tabs-pane) {
      padding: 10px 20px;
    }
    .checked-list {
      padding: 10px 20px;
      flex: 1;
    }
  }
</style>
